
package application;


import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import jeopardy.common.Utils;
import jeopardy.common.protocol.useraccount.UserAccountConsts;
import jeopardy.common.protocol.useraccount.UserAccountRequest;
import jeopardy.common.protocol.useraccount.UserAccountUtils;

import java.io.*;

/**
 * FXML Controller class
 *
 * @author Angie
 */
public class RegistrationScreenController implements Initializable, ControlledScreen {

	// Variables for reading input from the form
	@FXML
	private Text regMessage;
	@FXML
	private TextField userIDField;
	@FXML
	private TextField passwordField;
	
	private int accountCreated = 0;
	
	public String userName;
	public String passWord;
	public String rtPassword = "letmein123";
	
	ScreensController myController;
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    
    
    public void setScreenParent(ScreensController screenParent){
        myController = screenParent;
    }
    
    @FXML
    private void goToPostRegistrationScreen(ActionEvent event){
    	
		passWord = getPassword();
		userName = getUserName();

		// Make sure the input was valid
		// if (isEmpty(passWord) || isEmpty(userName) || (userName.length() > 11)) {
		if (!UserAccountUtils.validatePasswordString(passWord.toCharArray()) || !UserAccountUtils.validateUserString(userName)) {

			regMessage.setText("Either the User Name or the Password is invalid\n User Name should be at least between 6 & 12 characters long");
		} 
		else {
			try {
				createUserAccount();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	   
		if(accountCreated ==1 ) {
		    /* If the account creation  was successful, then bounce them
			to the login screen */ 
		    myController.setScreen(ScreensFramework.LoginScreenID);
		}

    }
    
	// Create user account for the requested user
	public int createUserAccount() throws UnknownHostException, IOException {
		byte[] returnCode = new byte[UserAccountConsts.USERACCOUNT_MAX_RES_LEN];
		
		try {
			SSLSocketFactory sslsocketfactory = ClientConsts.createSSLFactory();
			SSLSocket socket = (SSLSocket) sslsocketfactory.createSocket(
					ClientConsts.SERVER_IP, ClientConsts.SERVER_PORT);
			
			/* 
			 * Try to connect to the server - on success attempt to 
			   authenticate the user, otherwise display message
			*/
			if(socket.isConnected()) {
				System.out.println("Communication with server established - authenticating");
				regMessage.setText("Communication with server established - authenticating");

				
				UserAccountRequest uar = UserAccountUtils
						.createUserCreateRequest(userName, passWord.toCharArray());
				
				System.out.println("User name to send is: "+userName);
				System.out.println("Password to send is: "+passWord);
				
				socket.getOutputStream().write(
						UserAccountUtils.reqToNetworkMsg(uar));
				socket.getOutputStream().flush();
				
				
				// Read the response from the server and then parse it
				Utils.readBytes(socket.getInputStream(), returnCode);
				
				// Check the return code for authentication
				// Check the return code for authentication
				if(UserAccountUtils.parseUserAccountResponse(returnCode) ==  ClientConsts.authSuccess) {
					System.out.println("Account creation successful");
					regMessage.setText("Account Creation Successful");
					accountCreated = 1;
				}
				else {
					System.out.println("Account creation failure");
					regMessage.setText("Account creation failure");
				}
			}
			else {
				System.out.println("Failed to connect to the server");
				regMessage.setText("Unable to communicate with server");
			}
			
			
		} catch (Exception exception) {
			exception.printStackTrace();
			System.out.println("Failed to communicate to the server");
			regMessage.setText("Failed to communicate with server");
		}
		return 0;
	}

	// Get user name
	public String getUserName() {
		if (userIDField == null || isEmpty(userIDField.getText())) {
			return "";
		}
		return userIDField.getText();
	}

	// Get password
	public String getPassword() {
		if (passwordField == null || isEmpty(passwordField.getText())) {
			return "";
		}
		return passwordField.getText();
	}

	private boolean isEmpty(String s) {
		return s == null || s.trim().isEmpty();
	}
    
}
